package com.laihui.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.laihui.Constants;
import com.laihui.MyApplication;
import com.laihui.activity.BindCardActivity;
import com.laihui.activity.InviteActivity;
import com.laihui.activity.PlatformAnnouncementActivity;
import com.laihui.activity.QualityFinancingActivity;
import com.laihui.activity.R;

import com.laihui.activity.InvestContentActivity;
import com.laihui.activity.LoginActivity;
import com.laihui.activity.NewBigBagActivity;
import com.laihui.activity.PlatformAnnouncementDetailActivity;
import com.laihui.activity.RealnameActivity;
import com.laihui.activity.WebViewActivity;
import com.laihui.adapter.IndexBorrowRecordAdapter;
import com.laihui.base.BaseFragment;
import com.laihui.entity.Article;
import com.laihui.entity.MemberBank;
import com.laihui.entity.RealBean;
import com.laihui.utils.ToastUtil;
import com.laihui.view.CircleProgressView;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.taobao.library.BaseBannerAdapter;
import com.taobao.library.VerticalBannerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;



/**
 * Created by chensk on 2017/12/6.
 */

public class Index1Fragment extends BaseFragment {
    private static boolean isRealName = false;//是否实名认证的标志
    private static boolean isBindBankCard = false;//是否绑定银行卡的标志

    private Activity mActivity;
    //当前页数
    private int pageNum = 1;
    private static final String TAG = "Index1Fragment";
    boolean isStartBanner = false;
    private IndexBorrowRecordAdapter adapter;
    @BindView(R.id.easy_recycler_view)
    EasyRecyclerView easyRecyclerView;
    @BindView(R.id.btn_buy)//购买按钮
            Button btnBuy;
    @BindView(R.id.swipe_refresh)//刷新
            SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.tv_site_notice)//网站公告
            VerticalBannerView tvSiteNotice;
    @BindView(R.id.circleProgressBar)
    CircleProgressView circleProgressBar;
    @BindView(R.id.tv_loan_name)
    TextView tvLoanName;

    @BindView(R.id.tv_total_tender)
    TextView totalTender;
    @BindView(R.id.tv_total_user)
    TextView totalUser;

    @BindView(R.id.tv_loan_lowest_account)
    TextView tvLoanLowestAccount;


    @BindView(R.id.convenient_banner)//轮播图
            ConvenientBanner convenientBanner;

    @BindView(R.id.tv_time_limit)//轮播图
            TextView tvTimeLimit;




    private MyApplication application;
    private ArrayList<String> localImages = new ArrayList<>();//轮播图资源集合
    private ArrayList<String> pptUrl = new ArrayList<>();//链接集合




    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

            loadData();
            isReal();
            isBind();
        }
    }



    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.action.user.exit")) {

            } else if (intent.getAction().equals("android.action.toWithDraw")) {

            } else if (intent.getAction().equals("android.action.refresh")) {
                loadData();
                isBind();
                isReal();
                //getHotSale(true);
            }
        }
    };
    private void refresh() {
        isReal();
        isBind();
        loadData();

    }



    /**/
    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onPause() {
        super.onPause();
        convenientBanner.stopTurning();
    }
    @Override
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void init() {
        LinearLayoutManager linearLayout = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };
        mActivity = getActivity();
        application = (MyApplication) mActivity.getApplication();
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefresh.setRefreshing(false);
                refresh();
            }
        });
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(true);
                refresh();
                swipeRefresh.setRefreshing(false);
            }
        });
        easyRecyclerView.setLayoutManager(linearLayout);
        adapter = new IndexBorrowRecordAdapter(mActivity);
        easyRecyclerView.setAdapter(adapter);

       // circleProgressBar.setProgressNotInUiThread(0);
      //  circleProgressBar.setProgress(0);

        onClickBanner();

        loadData();

        easyRecyclerView.setErrorView(R.layout.error_layout);
        adapter.setMore(R.layout.load_none, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

            }
        });
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                if (!application.isLogin) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                } else {
                    if (!isRealName) {
                        Log.e(TAG, "onViewClicked: " + isRealName);
                        startActivity(new Intent(mActivity, RealnameActivity.class));
                        ToastUtil.showToast(mActivity, "您未进行实名认证");
                    } else if (!isBindBankCard) {
                        Log.e(TAG, "onViewClicked: " + isBindBankCard);
                        startActivity(new Intent(mActivity, BindCardActivity.class));
                        ToastUtil.showToast(mActivity, "您未绑定银行卡");
                    } else {
                        Intent intent = new Intent(mActivity, InvestContentActivity.class);
                        intent.putExtra("loan", adapter.getItem(position));
                        startActivity(intent);
                    }

                }
            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.action.user.exit");
        filter.addAction("android.action.toWithDraw");
        filter.addAction("android.action.refresh");
        mActivity.registerReceiver(receiver, filter);
        refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(receiver);
    }

    private void loadData() {
        Map<String, String> map = new HashMap<>();
        application.apiService.indexData(map)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<com.laihui.entity.Index>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("error", "onError: " + e.toString());
                    }

                    @Override
                    public void onNext(final com.laihui.entity.Index index) {
                        localImages.clear();
                        for (int i = 0; i < index.banners.size(); i++) {
                            localImages.add(Constants.BASE_URL_IMG + index.banners.get(i).img_src );
                            Log.e(TAG, "onNext: "+index.banners.get(i).img_src );
                            pptUrl.add(index.banners.get(i).img_link);
                        }
                        setBanner();
                        adapter.clear();
                        adapter.getAllData().clear();
                        adapter.addAll(index.loans);

                        adapter.notifyDataSetChanged();

                        if(index.rookie!=null){

                            tvLoanName.setText(index.rookie.name);
                            circleProgressBar.setmApr(index.rookie.apr.doubleValue());
                            circleProgressBar.setProgress((int) (new Double(index.rookie.amount_invested.toString() )/new Double( index.rookie.account.toString())*100));
                            tvLoanLowestAccount.setText(index.rookie.min_account.toString()+"起投");
                            if (index.rookie.is_day==1){
                                tvTimeLimit.setText("期限"+index.rookie.time_limit+"天");
                            }else{
                                tvTimeLimit.setText("期限"+index.rookie.time_limit+"个月");
                            }
                            btnBuy.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (!application.isLogin) {
                                        startActivity(new Intent(mActivity, LoginActivity.class));
                                    }else
                                    if (!isRealName) {
                                        startActivity(new Intent(mActivity, RealnameActivity.class));
                                        ToastUtil.showToast(mActivity, "您未进行实名认证");
                                    } else if (!isBindBankCard) {
                                        startActivity(new Intent(mActivity, BindCardActivity.class));
                                        ToastUtil.showToast(mActivity, "您未绑定银行卡");
                                    } else {

                                        Intent intent = new Intent(mActivity, InvestContentActivity.class);
                                        intent.putExtra("loan", index.rookie);

                                        startActivity(intent);
                                    }
                                }
                            });

                            totalUser.setText(index.registers+"");
                            totalTender.setText(index.totalTurnover+"");
                            if (index.articles.size() > 0) {
                                List<String> list = new ArrayList<>();
                                for (int i = 0; i < index.articles.size(); i++) {
                                    list.add(index.articles.get(i).title);
                                }
                                isStartBanner = !isStartBanner;
                                Index1Fragment.ContentBannerAdapter adapter = new Index1Fragment.ContentBannerAdapter(index.articles);
                                tvSiteNotice.setAdapter(adapter);
                                tvSiteNotice.start();
                            }
                        }

                    }

                });


    }
    class ContentBannerAdapter extends BaseBannerAdapter<Article> {

        private List<Article> mDatas;

        public ContentBannerAdapter(List<Article> datas) {
            super(datas);
            mDatas = datas;
        }

        @Override
        public View getView(VerticalBannerView parent) {
            return LayoutInflater.from(parent.getContext()).inflate(R.layout.item_banner_text, null);

        }

        @Override
        public void setItem(final View view, final Article data) {
//            TextView textView = new TextView(mActivity);

            TextView textView = (TextView) view.findViewById(R.id.tv_banner_text);

//            textView.setTextColor(Color.RED);
            textView.setText(data.title);
            //你可以增加点击事件
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mActivity, PlatformAnnouncementDetailActivity.class);
                    intent.putExtra("article", data);
                    startActivity(intent);

                }
            });
        }
    }



    private class LocalImageHolderView implements Holder<String> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, String data) {
            Glide.with(mActivity).load(data).into(imageView);
        }
    }

    /**
     * 设置轮播图
     *
     * @return
     */
    private void setBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<Index1Fragment.LocalImageHolderView>() {
            @Override
            public Index1Fragment.LocalImageHolderView createHolder() {
                return new Index1Fragment.LocalImageHolderView();
            }
        }, localImages)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.startTurning(5000);

    }

    @Override
    public void onStop() {
        super.onStop();
        tvSiteNotice.stop();
    }

    /**
     * 设置轮播图的点击跳转事件
     */
    private void onClickBanner() {
        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                String s = pptUrl.get(position);
                if (TextUtils.isEmpty(s) || "http://".equals(s)) {

                } else {
                    Intent intent = new Intent(mActivity, WebViewActivity.class);
                    Log.e(TAG, "onItemClick: "+pptUrl.get(position).toString() );
                    intent.putExtra("pptUrl", pptUrl.get(position).toString());
                    startActivity(intent);
                }
            }

        });
    }

    @Override
    public int getFragmentId() {
        return R.layout.fragment_index1;
    }

    @Override
    public Object bindFragment() {
        return this;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isStartBanner) {
            tvSiteNotice.start();
        }
    }

    //是否实名认证
    private void isReal() {
        Map<String, String> map = new HashMap<>();
        if(application.isLogin) {
            map.put("member_id", application.userId);
            application.apiService.toReal(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<RealBean>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(RealBean toRealname) {

                            if (toRealname.item != null) {
                                isRealName = true;
                            } else {
                                isRealName = false;
                            }
                        }
                    });
        }else{
            startActivity(new Intent(getActivity(),LoginActivity.class));
        }
    }

    //是否绑定银行卡
    private void isBind() {
        if(application.isLogin) {
            Map<String, String> map = new HashMap<>();
            map.put("member_id", application.userId);
            Log.e(TAG, "isBind: " + application.userId);
            application.apiService.isBankBind(map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<MemberBank>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }


                        public void onNext(MemberBank memberBank) {

                            if (memberBank.item==null) {
                              isBindBankCard =false;
                            } else  {
                                isBindBankCard =true;
                            }
                        }
                    });
        }else{
            startActivity(new Intent(getActivity(),LoginActivity.class));
        }
    }


    @OnClick({R.id.tv_site_notice,R.id.ll_financial, R.id.ll_new_gift, R.id.ll_invite,R.id.ll_project,R.id.ll_problem/*, R.id.ll_sign_in*/})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_new_gift:

                    Intent intent11 = new Intent(mActivity, NewBigBagActivity.class);
                    intent11.putExtra("url",Constants.BASE_URL+"api/rookie");
                    startActivity(intent11);

                break;
            case R.id.ll_invite:
                if (!application.isLogin) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                } else {

                    startActivity(new Intent(mActivity, InviteActivity.class));
                }
                break;


            case R.id. ll_problem:
                Intent intent =  new Intent(mActivity, PlatformAnnouncementActivity.class);
                intent.putExtra("cate_name","company");
                startActivity(intent);
                break;
            case R.id. ll_financial:

                Intent intent1 = new Intent(mActivity, QualityFinancingActivity.class);
                startActivity(intent1);
                break;


        }
    }

}